package org.sean.framework.auth.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import org.sean.framework.auth.captcha.GifCaptcha;
import org.sean.framework.auth.entity.Captcha;
import org.sean.framework.logging.Logger;
import org.springframework.stereotype.Service;

/**
 * 验证码
 */
@Service
public class CaptchaService {
    private final Logger logger = Logger.newInstance(getClass());

    /**
     * 获取普通文字验证码
     *
     * @return 验证码
     */
    public Captcha getCaptcha() {
        return getCaptcha(80, 250);
    }

    /**
     * 获取普通文字验证码
     *
     * @param heigth 高
     * @param width  宽
     * @return 验证码
     */
    public Captcha getCaptcha(int heigth, int width) {
        try {
            //生成文字验证码
            ShearCaptcha sc = CaptchaUtil.createShearCaptcha(width, heigth);
            Captcha captcha = new Captcha();
            captcha.setWords(sc.getCode());
            captcha.setImage(sc.getImageBase64Data());
            return captcha;
        } catch (Exception e) {
            logger.printStackTrace(e);
        }
        return null;
    }

    /**
     * 获取Gif文字验证码
     *
     * @return 验证码
     */
    public Captcha getGifCaptcha() {
        try {
            // gif格式验证码
            GifCaptcha gifCaptcha = new GifCaptcha(250, 80);
            Captcha captcha = new Captcha();
            captcha.setWords(gifCaptcha.getCode());
            captcha.setImage(gifCaptcha.getImageBase64Data());
            return captcha;
        } catch (Exception e) {
            logger.printStackTrace(e);
        }
        return null;
    }
}
